-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.c
45 lines (38 loc) · 970 Bytes
/
Solution.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <stdio.h>
int findMajorityElement(int arr[], int n) {
int count = 0, candidate = -1;
// Finding candidate
for (int i = 0; i < n; i++) {
if (count == 0) {
candidate = arr[i];
count = 1;
} else if (arr[i] == candidate) {
count++;
} else {
count--;
}
}
// Verifying candidate
count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == candidate)
count++;
}
return (count > n / 2) ? candidate : -1;
}
int main() {
int n;
printf("Enter the size of the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements of the array: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int result = findMajorityElement(arr, n);
if (result != -1)
printf("The majority element is: %d\n", result);
else
printf("No majority element found.\n");
return 0;
}